<template>
  <my-pannel headerTitle="Upload File Pannel">
    <el-col :span="24">
      <el-upload
        ref="upload"
        class="upload-file"
        action="#"
        multiple
        drag
        :show-file-list="false"
        :http-request="handleFileUpload"
        :before-upload="beforeUpload"
        :on-exceed="handleExceed"
        :limit="limitFileNumber"
        accept=".txt,.json"
      >
        <el-button type="primary"
          >Click to upload<el-icon style="margin-left: 5px"><Upload /></el-icon
        ></el-button>
        <template #tip>
          <div class="common-text" style="margin-top: 5px">
            please select a file in TEXT or JSON format.
          </div>
        </template>
      </el-upload>
    </el-col>
  </my-pannel>
</template>

<script>
import MyPannel from '@/components/MyPannel.vue';
import { ElMessage } from 'element-plus';
import { UploadTraObject } from '@/util/type/UploadTraObject';
import { mapState } from 'vuex';
export default {
  data() {
    return {
      filerSuffixs: ['txt', 'json'], //允许上传的文件类型后缀
      limitFileNumber: 10, //最大上传文件个数
      fileMaxSize: 20 * 1024 * 1024, //最大上传文件大小
    };
  },
  computed: {
    ...mapState(['traObjects']), //从vuex引入
  },
  methods: {
    //文件上传前，触发
    beforeUpload(file) {
      const fileExtension = file.name.split('.').pop().toLowerCase(); //获取文件的后缀
      //判断文件格式是否符合要求
      if (!this.filerSuffixs.includes(fileExtension)) {
        ElMessage.error(
          'The file format is incorrect. Currently, only TEXT and JSON format files are supported!',
        );
        return false;
      }
      //判断文件名是否符合要求
      if (/^\d+$/.test(file.name.split('.')[0]) || file.name.split('.')[0].indexOf('_') != -1) {
        ElMessage.error(
          "The file name does not meet the requirements and cannot have the character '_' and cannot be a pure number!",
        );
        return false;
      }
      //判断是否该文件名已经存在
      if (this.traObjects.length > 0) {
        const keyExists = this.traObjects.some(
          (item) => item['fileName'] === file.name.split('.')[0],
        );
        if (keyExists) {
          ElMessage.error('A file with the same name has already been uploaded!');
          return false;
        }
      }
      //判断文件大小是否超过上限
      if (file.size > this.fileMaxSize) {
        ElMessage.error(`File size exceeds the limit (${this.fileMaxSize / 1024 / 1024} MB)！`);
        return false;
      }
      return true;
    },
    //文件上传主要逻辑
    handleFileUpload(params) {
      const file = params.file; //获取文件对象
      const fileName = file.name.split('.')[0]; //获取文件名
      //判断文件大小是否超过上限的十分之一
      if (file.size >= 0.1 * this.fileMaxSize) {
        // 交给服务端进行解析
      } else {
        //浏览器端直接解析
        let reader = new FileReader(); // 解析上传的文件
        reader.readAsText(file);
        reader.onload = (e) => {
          //读取成功的回调
          const fileString = e.target.result; // 读取文件内容
          const coordsList = UploadTraObject.extractCoordsSeq(fileString); //坐标信息识别
          //判断是否有识别结果
          if (!coordsList) {
            ElMessage.error('The coordinate information was not resolved from the file!');
          } else {
            this.$store.commit(
              'updateTraObjects',
              new UploadTraObject(fileName, JSON.parse(coordsList)),
            ); //坐标序列提交到vuex中
            ElMessage.success('File upload and parsing successful!');
          }
        };
      }
    },
    //文件个数超限时触发
    handleExceed(files, fileList) {
      ElMessage.warning(
        `Exceeded file upload limit！Up to ${this.limitFileNumber} can be uploaded.`,
      );
    },
  },
  watch: {},
  components: {
    MyPannel,
  },
};
</script>

<style lang="scss" scoped></style>
